<script setup lang="jsx">
import {watch,inject,ref,nextTick,reactive,computed} from 'vue'
import AddModal from "@cps/actions/addModal.vue";
import waybill from '@/api/document/waybill'
import useShippingSchedule from "@/utils/crud/useShippingSchedule.js";
import shippingSchedule from "@/api/document/shippingSchedule.js";
import useSupplierService from "@/utils/crud/useSupplierService.js";
import supplierService from "@/api/logistics/supplierService.js";
import { Message, Modal } from '@arco-design/web-vue'
const columnsDist = inject('columnsDist')
// form 组件的 ref
const crudForm = ref()
const addModalRef = ref()
const crudFormShow=ref(false)
// 表单数据
const form = ref({id:''})
const visible = ref(false)
const updateShow=ref(false)
  const onShow = async (value) => {
    crudForm.value.resetForm();
    console.log('updateShow.value',updateShow.value)
    updateShow.value=true
      visible.value = true
    if(value){
      console.log('value',value)
      form.value=JSON.parse(JSON.stringify(value))
      if(form.value.type){
        form.value.type=form.value.type.toString()
      }
      if(form.value.shipping_schedule_id==0){
        form.value.shipping_schedule_id=null
      }
      if(form.value.single_card_user_id){
        form.value.single_card_user_id=form.value.single_card_user_id.toString()
      }
      if(form.value.depot_id){
        form.value.depot_id=form.value.depot_id.toString()
      }
      if(form.value.channel_admin_id){
        form.value.channel_admin_id=form.value.channel_admin_id.toString()
      }
      if(form.value.finance_id){
        form.value.finance_id=form.value.finance_id.toString()
      }
    }
    
  }
  const options = ref({
    showButtons:false,
  })
  const columns=  ref(
    [
  {
   
        formType: 'grid-tailwind',
        colNumber: 2,      
        cols: [
          {
            formList: [{
              dataIndex: 'type', title: '类型',formType: "radio",type: 'button', 
              dict: {
                  data:columnsDist.value.dictObj.data.flrstLegType,
                  props: {label: 'title', value: 'key'}, translation: true,
              },
              rules: [{ required: true, message: '请选择类型' }],
              virtualListProps:{},
              fixed: 'left',
                width: 140,
                onChange: async (value, maFormObject) => {
                  let formData = maFormObject.formModel.value
                  delete formData.shipping_schedule_id
                  delete formData.supplier_service_id
                  delete formData.departure
                  delete formData.destination
                  let dict = maFormObject.getColumnService().dicts
                  // 提单类型切换
                  let columnService = maFormObject.getColumnService()
                  columnService.get('shipping_schedule_id').setAttr('display', true)
                  columnService.get('supplier_service_id').setAttr('display', true)
                  columnService.get('departure').setAttr('display', true)
                  columnService.get('destination').setAttr('display', true)
                  // // 切换船期类型
                  // columnService.getDictService('shipping_schedule_id').loadDict(dicthelpApi.shipping_schedule_with_type(value), dict)
                  // // 切换供应商服务
                  // columnService.getDictService('supplier_service_id').loadDict(dicthelpApi.supplier_service_with_type(value), dict)
                  // // 切换出发地,目的地
                  // columnService.getDictService('departure').loadDict(dicthelpApi.place_with_type(value), dict)
                  // columnService.getDictService('destination').loadDict(dicthelpApi.place_with_type(value), dict)
                },
                onControl: (val, maFormObject) => {
                  if (form.value.id != '' && updateShow.value) {
                        return{                
                          shipping_schedule_id: {display: !!val,},
                          supplier_service_id: {display: !!val,},
                          departure: {display: !!val,},
                          destination: {display: !!val,},                                              
                        }
                    }
                }
            },{
              dataIndex: 'number', title: '客户提单号', 
              rules: [{ required: true, message: '请输入客户提单号' }]
            },
            {
                title: "船期/航班",
                dataIndex: "shipping_schedule_id",
                formType: "tree-select",
                // formType: "select",

                display:false,
                fieldNames:{
                  key: 'id',
                  title: 'name',
                  children: 'children'
                },
                dict: {               
                    data:columnsDist.value.dicthelpApi_shipping_schedule.data,
                    // 指定组件接收的props
                    // props: {label: 'name', value: 'id',},
                    translation: true,
                },
                addApi: () => {
                  addModalRef.value.open(useShippingSchedule.columns, {
                    viewType: 'modal',
                    width: '70%',
                    layout: useShippingSchedule.layout,
                  }, shippingSchedule.save)
                },
                onChange: async (value, maFormObject) => {
                    let formData = maFormObject.formModel.value
                    const keysMap = {
                      'departure': 'departure',
                      'destination': 'destination',
                      'supplier_service_id': 'supplier_service_id',
                      'close_at': 'close_at',             
                    }
                    // 清空
                    if (!value) {
                      for (const columnServiceKey in keysMap) {
                        formData[keysMap[columnServiceKey]] = null
                      }
                      return
                    }
                    // 船期信息填充
                    let dict = maFormObject.getColumnService().dicts['shipping_schedule_id'].find(i => i.value === value)
                    console.log(dict)
                    if (dict && dict.data) {
                      for (const columnServiceKey in keysMap) {
                        formData[keysMap[columnServiceKey]] = dict.data[columnServiceKey]
                      }
                    }
                  },
            },
            {
              title: "供应商",
              dataIndex: "supplier_service_id",
              formType: "select",
              display:false,
              addApi: () => {
                addModalRef.value.open(useSupplierService.columns, {
                  viewType: 'modal',
                }, supplierService.save)
              },
              addApiAuth: 'logistics:supplierService:save',
              dict: {
                data:columnsDist.value.dicthelpApi_supplier_service.data,
                props: {label: 'name', value: 'id'}, translation: true,
              },
              
            },
            {
              title: "出发地",
              dataIndex: "departure",
              formType: "select",
              display:false,
              dict: {
                data:columnsDist.value.dicthelpApi_place.data,
                props: {label: 'name', value: 'id'}, translation: true,
              },
              rules: {
                required: true,
                message: "请输入出发地"
              },
            },
            {
              title: "目的地",
              dataIndex: "destination",
              formType: "select",
              display:false,
              dict: {
                data:columnsDist.value.dicthelpApi_place.data,
                props: {label: 'name', value: 'id'}, translation: true,
              },
              rules: {
                required: true,
                message: "请输入目的地"
              },
            },
            {title: "出发时间", dataIndex: "departure_at", formType: "date", showTime: true},
            {title: "到站时间", dataIndex: "arrived_at", formType: "date", showTime: true},
            {title: "清关时间", dataIndex: "clear_at", formType: "date", showTime: true},
            {title: "截单时间", dataIndex: "close_at", formType: "date", showTime: true},
            {title: "报关代理", dataIndex: "declare_id", formType: "select",
               dict: {
                data:columnsDist.value.dicthelpApi_supplier_declare.data,
                props: {label: 'name', value: 'id'}, translation: true,
              },
            },
            {title: "清关公司", dataIndex: "clearance_id", formType: "select",
               dict: {
                data:columnsDist.value.dicthelpApi_supplier_clearance.data,
                props: {label: 'name', value: 'id'}, translation: true,
              },
            },
            {title: "集装箱规格", dataIndex: "container_type", formType: "select",
               dict: {
                data:columnsDist.value.dictObj.data.containerType,
                props: {label: 'title', value: 'key'}, translation: true,
              },
            },
          ]
          },
          {
            formList: [
            {title: "单证员", dataIndex: "single_card_user_id", formType: "select",
               dict: {
                data:columnsDist.value.dicthelpApi_user.data,
                props: {label: 'nickname', value: 'id'}, translation: true,
              },
            },{
              dataIndex: 'container_no', title: '柜号',
            },
            {
              dataIndex: 'seal_no', title: '铅封号',
            },
            {title: "货站", dataIndex: "depot_id", formType: "select",
               dict: {
                data:columnsDist.value.dicthelpApi_depot.data,
                props: {label: 'name', value: 'id'}, translation: true,
              },
            },
            {title: "渠道管理员", dataIndex: "channel_admin_id", formType: "select",
               dict: {
                data:columnsDist.value.dicthelpApi_user.data,
                props: {label: 'nickname', value: 'id'}, translation: true,
              },
            },
            {title: "财务", dataIndex: "finance_id", formType: "select",
               dict: {
                data:columnsDist.value.dicthelpApi_user.data,
                props: {label: 'nickname', value: 'id'}, translation: true,
              },
            },
            {
              dataIndex: 'carrier', title: '承运商',
              formType: "select",
              dict: {
                  name: "waybill_carrier",
                  props: {
                    label: "title",
                    value: "key"
                  },
                  translation: true
                }
            },
            {
              dataIndex: 'route', title: '路由',formType: "radio",
              addDefaultValue: "1",
              dict:{
                data:[
                  {value: '1', label: '追踪'},
                  {value: "0", label: '不追踪'},
                ]
              }
            },
            {
              dataIndex: 'remark', title: '备注',formType: "textarea",
            },
            // {
            //   dataIndex: 'internal_remark', title: '内部备注',formType: "textarea",
            // },
          ]
          },         
        ]
      },
    ]
  )
  
const emits = defineEmits(['addClick','emitClick'])
const formLoading=ref(false)
  //新增 //编辑
  const handleBeforeOk =async () => {
    if (await crudForm.value.validateForm()) {
      return false
    }
    console.log('form',form)
    formLoading.value=true
          if(form.value.id==''){
            waybill.save(form.value).then(res => {
              if(res.success){
                Message.success(res.message || `新增成功！`);
              emits('addClick');
              close()
              }else{
                Message.warning(res.message)

              }
              
            }).finally(()=>{
              formLoading.value=false
            })
          }else{
            waybill.update(form.value).then(res => {
              if(res.success){
                Message.success(res.message || `编辑成功！`)    
              emits('emitClick');
              close()
              }else{
                Message.warning(res.message)

              }
            }).finally(()=>{
              formLoading.value=false
            })
          }
      
    };
    const close = () => {
      visible.value = false
    }
const onBeforeCancel=()=>{
  Modal.confirm({
        title: '确认关闭?',
        onOk: () => {
          close()
        },
      });
}
nextTick(() => {
    crudFormShow.value=true
})
defineExpose({ onShow })
</script>

<template>
  <a-drawer v-model:visible="visible" width="80%" :onBeforeCancel="onBeforeCancel">
    <template #title><div >{{  form.id == "" ? '新增' : '编辑'}}</div></template>
    <ma-form  v-model="form" ref="crudForm" :options="options" :columns="columns">
      </ma-form>
      <template #footer>        
          <a-button @click="onBeforeCancel">关闭</a-button>
          <a-button type="primary" :disabled="formLoading" @click="handleBeforeOk(crudForm)">
            保存
          </a-button>
        </template>
        <add-modal ref="addModalRef"></add-modal>
  </a-drawer>
</template>